<template autoRoute="true">
  <div class="calendar-container">
    <!-- 日历头部 -->
    <div class="calendar-header">
      <div class="calendar-controls">
        <el-button @click="goToday" size="small">今天</el-button>
        <el-button
          @click="navigatePeriod(-1)"
          :icon="ArrowLeft"
          text
        ></el-button>
        <span class="current-month">{{ currentMonthText }}</span>
        <el-button
          @click="navigatePeriod(1)"
          :icon="ArrowRight"
          text
        ></el-button>
        <el-tooltip
          class="box-item"
          effect="dark"
          content="刷新"
          placement="right"
        >
          <el-icon style="cursor: pointer" @click="refreshCalendar"
            ><Refresh
          /></el-icon>
        </el-tooltip>
      </div>
      <div class="calendar-view-switch">
        <el-radio-group v-model="currentView" size="small" @change="changeView">
          <el-radio-button label="day">日</el-radio-button>
          <el-radio-button label="week">周</el-radio-button>
          <el-radio-button label="month">月</el-radio-button>
        </el-radio-group>
      </div>
    </div>
    <!-- 日历内容 -->
    <div
      id="calendarContainer"
      class="calendar-content"
      style="width: 100%; height: calc(100vh - 110px)"
    ></div>

    <!-- 统一的事件Dialog（新增/编辑共用） -->
    <el-dialog
      v-model="eventDialogVisible"
      :title="isViewMode ? eventFormData.title : '未命名记录'"
      width="400px"
      :show-close="false"
      :before-close="closeEventDialog"
      :style="{
        left: dialogPosition.left,
        top: dialogPosition.top,
        transform: 'none',
        position: 'fixed',
        zIndex: 2050,
      }"
      :modal="false"
    >
      <div class="event-form">
        <el-form :model="eventFormData" label-width="60px" size="small">
          <el-form-item label="任务描述">
            <el-input
              v-model="eventFormData.title"
              placeholder="请输入内容"
              :disabled="isViewMode"
            ></el-input>
          </el-form-item>
          <el-form-item label="日期选择">
            <el-date-picker
              v-model="eventFormData.durationDate"
              type="daterange"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD HH:mm"
              style="width: 100%"
              :disabled="isViewMode"
            />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <div class="event-form-actions">
          <el-button size="small" @click="switchToEditMode()">编辑</el-button>
          <el-button size="small" type="danger" @click="confirmDeleteEvent"
            >删除</el-button
          >
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
  import { onMounted, onUnmounted, ref, computed, nextTick } from "vue";
  // @ts-ignore - 忽略@toast-ui/calendar的类型声明文件问题
  import Calendar from "@toast-ui/calendar";
  import "@toast-ui/calendar/dist/toastui-calendar.min.css";
  // import "tui-date-picker/dist/tui-date-picker.css";
  // import "tui-time-picker/dist/tui-time-picker.css";

  import {
    ElButton,
    ElRadioGroup,
    ElRadioButton,
    ElForm,
    ElFormItem,
    ElInput,
    ElDatePicker,
    ElMessage,
    ElMessageBox,
  } from "element-plus";
  import { ArrowLeft, ArrowRight, Refresh } from "@element-plus/icons-vue";
  import type { ProjectNode } from "@/components/CLTable/interface.ts";
  import { useRouter } from "vue-router";
  import { deleteTask } from "@/api/project.ts";
  interface calendarProps {
    initialData?: ProjectNode[];
  }
  const props = defineProps<calendarProps>();
  // 日历实例引用
  let calendarInstance: any = null;
  const currentDate = ref(new Date());
  const currentView = ref("week");

  const dayNames = ["周日", "周一", "周二", "周三", "周四", "周五", "周六"];
  const getDayName = (day: number) => {
    return dayNames[day];
  };

  // 统一的Dialog相关状态
  const eventDialogVisible = ref(false);
  const isViewMode = ref(true); // 标记当前是查看模式还是编辑模式
  const dialogPosition = ref({ left: "0px", top: "0px" }); // 对话框位置

  // 统一的事件表单数据
  const eventFormData = ref({
    id: "",
    calendarId: "",
    title: "",
    durationDate: "",
  });

  // 计算当前月份文本
  const currentMonthText = computed(() => {
    const year = currentDate.value.getFullYear();
    const month = currentDate.value.getMonth() + 1;
    return `${year}年${month}月`;
  });

  // 生成随机颜色
  const getRandomColor = () => {
    // 预设的一组美观颜色
    const colors = [
      "rgb(158, 95, 255)", // 紫色
      "rgb(0, 169, 255)", // 蓝色
      "rgb(3, 189, 158)", // 青色
      "rgb(187, 220, 0)", // 黄绿色
      "rgb(219, 71, 63)", // 红色
      "rgb(255, 149, 0)", // 橙色
      "rgb(255, 87, 34)", // 深橙色
      "rgb(103, 58, 183)", // 深紫色
      "rgb(100, 181, 246)", // 亮蓝色
      "rgb(76, 175, 80)", // 绿色
    ];
    return colors[Math.floor(Math.random() * colors.length)];
  };

  const generateEvents = () => {
    const events: any[] = [];
    if (props.initialData && Array.isArray(props.initialData)) {
      props.initialData.forEach((item, index) => {
        const startDate = new Date(item.plannedStartTime);
        const endDate = new Date(item.plannedEndTime);

        // 时间差（毫秒转换为小时）
        const diffHours = (endDate - startDate) / (1000 * 60 * 60);

        // 判断是否为全天事件：≥24 小时 或 跨天且时间为 00:00-00:00
        const isAllDay =
          diffHours >= 24 ||
          (startDate.getHours() === 0 &&
            startDate.getMinutes() === 0 &&
            endDate.getHours() === 0 &&
            endDate.getMinutes() === 0);

        // 颜色处理
        const randomColor = getRandomColor();
        events.push({
          id: item.id,
          calendarId: item.calendarId || "cal1",
          title: item.name || `未命名事件 ${index}`,
          start: item.plannedStartTime,
          end: item.plannedEndTime,
          attendees: item.attendees || [],
          category: isAllDay ? "allday" : "time",
          isAllDay,
          backgroundColor: item.backgroundColor || randomColor,
          color: item.color || "#ffffff",
          borderColor: item.borderColor || randomColor,
          projectId: item.projectId,
        });
      });
    }
    console.log("events", events);
    return events;
  };

  // 重置事件表单数据
  const resetEventForm = () => {
    eventFormData.value = {
      id: "",
      calendarId: "",
      title: "",
      // startDate: "",
      // endDate: "",
      durationDate: "",
    };
  };

  // 保存事件（新增或更新）
  const saveEvent = () => {
    if (
      !eventFormData.value.title ||
      !eventFormData.value.durationDate ||
      !eventFormData.value.durationDate[0] ||
      !eventFormData.value.durationDate[1]
    ) {
      ElMessage({
        message: `请填写：${!eventFormData.value.title ? "任务描述" : ""}${
          !eventFormData.value.durationDate[0] ? "开始时间" : ""
        }${!eventFormData.value.durationDate[1] ? "结束时间" : ""}`,
        type: "warning",
      });
      return;
    }
    // console.log("eventFormData", eventFormData.value)
    if (isViewMode.value) {
      // 更新现有事件
      const changes = {
        title: eventFormData.value.title,
        start: new Date(eventFormData.value.durationDate[0]).toISOString(),
        end: new Date(eventFormData.value.durationDate[1]).toISOString(),
      };

      if (calendarInstance) {
        calendarInstance.updateEvent(
          eventFormData.value.id,
          eventFormData.value.calendarId,
          changes,
        );
      }
    } else {
      // 创建新事件
      const randomColor = getRandomColor();
      const eventData = {
        id: `event-${new Date().getTime()}`,
        calendarId: "cal1",
        title: eventFormData.value.title,
        start: eventFormData.value.durationDate[0],
        end: eventFormData.value.durationDate[1],
        category: "time",
        isAllDay: false,
        backgroundColor: randomColor,
        color: "#ffffff",
        borderColor: randomColor,
      };
      console.log("eventData", eventData);
      if (calendarInstance) {
        calendarInstance.createEvents([eventData]);
      }
    }

    closeEventDialog();
  };

  // 关闭事件弹窗
  const closeEventDialog = () => {
    eventDialogVisible.value = false;
    resetEventForm();
    isViewMode.value = true; // 重置为查看模式
    calendarInstance.clearGridSelections();
  };
  const router = useRouter();
  const switchToEditMode = () => {
    router.push({
      path: "/SubTaskView",
      query: {
        taskId: eventFormData.value.id,
      },
    });
  };

  // 确认删除事件
  const confirmDeleteEvent = () => {
    ElMessageBox.confirm("确定要删除这个事件吗？", "删除确认", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
    })
      .then(async () => {
        // 执行删除操作
        if (calendarInstance && eventFormData.value.id) {
          calendarInstance.deleteEvent(
            eventFormData.value.id,
            eventFormData.value.calendarId,
          );
          await deleteTask(eventFormData.value.id);
          ElMessage({
            type: "success",
            message: "删除成功",
          });
        }
        closeEventDialog();
      })
      .catch(() => {
        // 用户取消删除
      });
  };

  // 计算对话框位置并处理碰撞
  const calculateDialogPosition = (nativeEvent?: Event) => {
    if (!nativeEvent || !(nativeEvent instanceof MouseEvent)) {
      dialogPosition.value = { left: "50%", top: "50%" };
      return;
    }

    const clickX = nativeEvent.clientX;
    const clickY = nativeEvent.clientY;

    const dialogWidth = 400;
    const dialogHeight = 350;

    // 获取视口尺寸
    const viewportWidth = window.innerWidth;
    const viewportHeight = window.innerHeight;

    // 计算对话框位置（默认显示在点击位置右侧）
    let left = clickX + 10;
    let top = clickY - dialogHeight / 2;

    if (left + dialogWidth > viewportWidth) {
      left = clickX - dialogWidth - 10;
    }

    if (top < 20) {
      top = 20;
    }

    if (top + dialogHeight > viewportHeight) {
      top = viewportHeight - dialogHeight - 20;
    }

    dialogPosition.value = {
      left: `${left}px`,
      top: `${top}px`,
    };
  };

  // 显示新增事件Dialog
  // const showCreateDialog = (eventInfo: {
  //   start: Date;
  //   end: Date;
  //   nativeEvent: Event;
  // }) => {
  //   // 检查当前是否已经有编辑弹窗打开
  //   if (eventDialogVisible.value) {
  //     // 如果编辑弹窗已打开，则不打开新增弹窗
  //     return;
  //   }
  //   isViewMode.value = false;
  //
  //   // 设置默认时间
  //   const start = eventInfo.start;
  //   const startDate = `${start.getFullYear()}-${String(start.getMonth() + 1).padStart(2, "0")}-${String(start.getDate()).padStart(2, "0")} ${String(start.getHours()).padStart(2, "0")}:${String(start.getMinutes()).padStart(2, "0")}`;
  //   const end = new Date(start.getTime() + 60 * 60 * 1000); // 默认1小时
  //   const endDate = `${end.getFullYear()}-${String(end.getMonth() + 1).padStart(2, "0")}-${String(end.getDate()).padStart(2, "0")} ${String(end.getHours()).padStart(2, "0")}:${String(end.getMinutes()).padStart(2, "0")}`;
  //
  //   eventFormData.value = {
  //     id: "",
  //     calendarId: "cal1",
  //     title: "",
  //     durationDate: [startDate, endDate],
  //     // startDate: `${start.getFullYear()}-${String(start.getMonth() + 1).padStart(2, "0")}-${String(start.getDate()).padStart(2, "0")} ${String(start.getHours()).padStart(2, "0")}:${String(start.getMinutes()).padStart(2, "0")}`,
  //     // endDate: `${end.getFullYear()}-${String(end.getMonth() + 1).padStart(2, "0")}-${String(end.getDate()).padStart(2, "0")} ${String(end.getHours()).padStart(2, "0")}:${String(end.getMinutes()).padStart(2, "0")}`,
  //   };
  //   console.log("eventFormData", eventFormData.value);
  //   // 计算对话框位置
  //   calculateDialogPosition(eventInfo.nativeEvent);
  //
  //   // 显示Dialog
  //   nextTick(() => {
  //     eventDialogVisible.value = true;
  //   });
  // };

  // 显示编辑事件Dialog
  const showEditDialog = (eventData: any, nativeEvent?: Event) => {
    // 设置为查看模式
    isViewMode.value = true;

    // 设置编辑表单数据
    const startDate = new Date(eventData.start);
    const endDate = new Date(eventData.end);
    const start = `${startDate.getFullYear()}-${String(startDate.getMonth() + 1).padStart(2, "0")}-${String(startDate.getDate()).padStart(2, "0")} ${String(startDate.getHours()).padStart(2, "0")}:${String(startDate.getMinutes()).padStart(2, "0")}`;
    const end = `${endDate.getFullYear()}-${String(endDate.getMonth() + 1).padStart(2, "0")}-${String(endDate.getDate()).padStart(2, "0")} ${String(endDate.getHours()).padStart(2, "0")}:${String(endDate.getMinutes()).padStart(2, "0")}`;

    eventFormData.value = {
      id: eventData.id,
      calendarId: eventData.calendarId,
      title: eventData.title,
      durationDate: [start, end],
    };
    console.log("eventFormData", eventFormData.value);
    // 计算对话框位置
    calculateDialogPosition(nativeEvent);

    // 显示编辑Dialog
    nextTick(() => {
      eventDialogVisible.value = true;
    });
  };

  const initCalendar = () => {
    try {
      // 销毁已存在的实例
      if (calendarInstance) {
        calendarInstance.destroy();
        calendarInstance = null;
      }

      const container = document.getElementById("calendarContainer");
      if (!container) {
        console.error("未找到日历容器");
        return;
      }

      // 生成事件数据
      const events = generateEvents();

      const options = {
        usageStatistics: false,
        // 基础配置
        defaultView: currentView.value,
        view: currentView.value,
        template: {
          milestone: function (model: any) {
            return (
              '<span class="calendar-font-icon ic-milestone-b"></span> <span style="background-color: ' +
              model.bgColor +
              '">' +
              model.title +
              "</span>"
            );
          },
          titlePlaceholder: function () {
            return "输入标题";
          },
          locationPlaceholder: function () {
            return "输入地点";
          },
          startDatePlaceholder: function () {
            return "开始时间";
          },
          endDatePlaceholder: function () {
            return "结束时间";
          },
          popupIsAllday() {
            return "全天";
          },
          popupStateFree() {
            return "Free";
          },
          popupEdit() {
            return "编辑";
          },
          popupDelete() {
            return "删除";
          },
          popupDetailTitle({ title }: { title: string }) {
            return title;
          },
          popupDetailLocation({ location }: { location: string }) {
            return location;
          },
          popupSave() {
            return `<span style="color: #fff;">保存</span>`;
          },
          popupUpdate() {
            return `<span style="color: #fff;">确定</span>`;
          },
          monthMoreTitleDate: function (moreTitle: {
            date: string;
            day: number;
          }) {
            const { date, day } = moreTitle;
            const dayName = getDayName(day);
            return `<span class="toastui-calendar-more-title-date">${date}</span><span class="toastui-calendar-more-title-day">${dayName}</span>`;
          },
        },
        theme: {
          common: {
            holiday: {
              color: "#141414",
            },
            dayName: {
              color: "#141414",
            },
          },
          month: {
            dayExceptThisMonth: {
              color: "rgba(51, 51, 51, 0.4)",
            },
            weekend: {
              backgroundColor: "#F9F9F9",
            },
            holidayExceptThisMonth: {
              color: "rgba(51, 51, 51, 0.4)",
            },
          },
          week: {
            dayGridLeft: {
              // backgroundColor: "#ae2525",
            },
          },
        },
        // 弹窗配置
        useFormPopup: false,
        useDetailPopup: false,

        // 时间配置
        timeZone: "Asia/Beijing",
        renderSidebar: true,
        isReadOnly: false,
        week: {
          dayNames: dayNames,
          startDayOfWeek: 0,
          showNowIndicator: true,
          hourStart: 8,
          hourEnd: 22,
          eventView: ["allday"],
          taskView: ["milestone", "task"],
          // narrowWeekend: true,
          // timezonesCollapsed: true,
        },
        month: {
          dayNames: dayNames,
          startDayOfWeek: 0,
          isAlways6Weeks: true,
        },
        // 在Options未发现day配置
        // day: {
        //   dayNames: dayNames,
        //   showNowIndicator: true,
        //   hourStart: 8,
        //   hourEnd: 22,
        // },
      };

      // 创建日历实例
      calendarInstance = new Calendar(container, options);
      calendarInstance.createEvents(events);

      // 事件监听
      calendarInstance.on("beforeCreateEvent", (eventObj: any) => {
        calendarInstance.createEvents([
          {
            ...eventObj,
            id: new Date().getTime().toString(),
          },
        ]);
      });
      calendarInstance.on("beforeUpdateEvent", (eventObj: any) => {
        console.log("修改", eventObj);
        const targetEvent = eventObj.event;
        const changes = { ...eventObj.changes };
        calendarInstance.updateEvent(
          targetEvent.id,
          targetEvent.calendarId,
          changes,
        );
      });
      calendarInstance.on("beforeDeleteEvent", (eventObj: any) => {
        console.log("删除", eventObj);
        calendarInstance.deleteEvent(eventObj.id, eventObj.calendarId);
      });

      calendarInstance.on(
        "selectDateTime",
        (eventInfo: {
          start: Date;
          end: Date;
          isAllday: boolean;
          nativeEvent: Event;
        }) => {
          console.log("选择时间", eventInfo);
          if (eventDialogVisible.value) {
            calendarInstance.clearGridSelections();
            return;
          }
          // calendarInstance.clearGridSelections();
          // setTimeout(() => {
          //   showCreateDialog(eventInfo);
          // }, 200);
        },
      );
      calendarInstance.on(
        "clickDayName",
        (eventInfo: {
          start: Date;
          end: Date;
          isAllday: boolean;
          nativeEvent: Event;
        }) => {
          console.log("点击日期", eventInfo);
        },
      );
      calendarInstance.on(
        "clickEvent",
        ({ event, nativeEvent }: { event: any; nativeEvent: Event }) => {
          if (nativeEvent && nativeEvent.stopPropagation) {
            nativeEvent.stopPropagation();
          }
          console.log("点击事件", event);
          calendarInstance.clearGridSelections();

          closeEventDialog();
          // 延迟显示编辑弹窗，确保其他事件处理完成
          setTimeout(() => {
            showEditDialog(event, nativeEvent);
          }, 200);
        },
      );

      console.log("日历初始化完成，事件数据已设置:", events.length, "个事件");
    } catch (error) {
      console.error("初始化日历失败:", error);
    }
  };

  // 切换到今天
  const goToday = () => {
    if (calendarInstance) {
      calendarInstance.today();
      currentDate.value = new Date();
    }
  };

  // 导航到上一个/下一个周期
  const navigatePeriod = (direction: number) => {
    if (calendarInstance) {
      const date = new Date(currentDate.value);
      switch (currentView.value) {
        case "day":
          date.setDate(date.getDate() + direction);
          break;
        case "week":
          date.setDate(date.getDate() + direction * 7);
          break;
        case "month":
        default:
          date.setMonth(date.getMonth() + direction);
          break;
      }
      currentDate.value = date;
      if (direction < 0) {
        calendarInstance.prev();
      } else {
        calendarInstance.next();
      }
    }
  };

  // 切换视图
  const changeView = () => {
    if (calendarInstance) {
      calendarInstance.changeView(currentView.value);
    }
  };

  // 刷新日历
  const refreshCalendar = () => {
    initCalendar();
  };

  // 处理窗口大小变化
  const handleResize = () => {
    if (calendarInstance) {
      // @toast-ui/calendar v2 支持resize方法
      if (typeof calendarInstance.resize === "function") {
        calendarInstance.resize();
      } else {
        // 如果没有resize方法，则重新初始化日历
        initCalendar();
      }
    }
  };

  // 组件挂载
  onMounted(() => {
    nextTick(() => {
      initCalendar();
      // 添加窗口大小变化监听
      window.addEventListener("resize", handleResize);
    });
  });

  // 组件卸载
  onUnmounted(() => {
    // 移除窗口大小变化监听
    window.removeEventListener("resize", handleResize);
    if (calendarInstance) {
      calendarInstance.destroy();
      calendarInstance = null;
    }
  });
</script>

<style lang="scss" scoped>
  .calendar-container {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
  }

  .calendar-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 10px 16px;
    background-color: #ffffff;
    margin-bottom: 10px;
  }

  .calendar-controls {
    display: flex;
    align-items: center;
    gap: 12px;
  }

  .current-month {
    font-size: 16px;
    font-weight: 600;
    color: #333;
    min-width: 100px;
    text-align: center;
  }

  .calendar-content {
    width: 100%;
    height: 800px;
    background-color: #ffffff;
    border-radius: 8px;
    overflow: hidden;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  }

  // 针对@toast-ui/calendar v2版本的样式调整
  :deep(.tui-full-calendar) {
    font-family:
      -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
  }

  :deep(.tui-calendar-weekday-grid-line) {
    border-left: 1px solid #f0f0f0;
  }

  :deep(.tui-calendar-weekday-grid-line:last-child) {
    border-right: 1px solid #f0f0f0;
  }

  :deep(.tui-full-calendar-weekday-schedule) {
    border-radius: 4px;
    margin: 1px;
  }

  // v2版本额外样式调整
  :deep(.tui-calendar-section-header) {
    background-color: #f7f7f7;
  }

  :deep(.tui-calendar-time-schedule) {
    opacity: 0.9;
  }

  :deep(.tui-calendar-today) {
    background-color: #e8f4fd;
  }

  // Dialog相关样式
  .event-form {
    padding: 16px;
  }

  .event-form-title {
    margin-top: 0;
    margin-bottom: 16px;
    font-size: 16px;
    font-weight: 600;
    color: #333;
  }

  .event-form-actions {
    display: flex;
    justify-content: flex-end;
  }
</style>
<style>
  .toastui-calendar-see-more {
    min-height: 110px !important;
  }
  .toastui-calendar-more-title-day {
    font-size: 12px;
    color: #999;
    margin-left: 4px;
  }
  .toastui-calendar-panel::-webkit-scrollbar {
    display: none;
  }
</style>
